package net.love5z.web.controller;

import java.net.URLDecoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.love5z.web.common.utils.ObjectPropUtils;
import net.love5z.web.controller.model.User;
import net.love5z.web.service.UserService;
import net.love5z.web.service.bo.CheckUserLoginResult;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class LoginController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/user/login.aspx", method = RequestMethod.GET)
    public String preLogin(ModelMap map, HttpServletRequest request, HttpServletResponse response)
                                                                                                  throws Exception {
        String redirect = URLDecoder.decode(request.getParameter("redirect"), "UTF-8");
        map.put("redirect", redirect);
        return "user/login.vm";
    }

    @RequestMapping(value = "/user/login.aspx", method = RequestMethod.POST)
    public String login(ModelMap map, String email, String password, HttpServletRequest request,
                        HttpServletResponse response) throws Exception {
        if (StringUtils.isBlank(email)) {
            map.addAttribute("error", "Please Input Email!");
            return "user/login.vm";
        }

        if (StringUtils.isBlank(password)) {
            map.addAttribute("error", "Please Input Password!");
            return "user/login.vm";
        }

        CheckUserLoginResult checkUserLoginResult = userService.checkUserLogin(email, password);

        if (checkUserLoginResult.isSuccess()) {
            User user = (User) ObjectPropUtils.createAndCopyProperties(
                checkUserLoginResult.getUserBo(), User.class);

            HttpSession session = request.getSession();
            session.setAttribute("SESSION_IS_LOGIN", Boolean.TRUE);
            session.setAttribute("SESSION_LOGIN_USER", user);

            String redirect = URLDecoder.decode(request.getParameter("redirect"), "UTF-8");

            return "redirect:" + redirect;
        } else {
            map.addAttribute("error", checkUserLoginResult.getErrorMsg());
            return "user/login.vm";
        }

    }

    @RequestMapping(value = "/user/logout.aspx", method = RequestMethod.GET)
    public String logout(ModelMap map, HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
        session.setAttribute("SESSION_IS_LOGIN", Boolean.FALSE);
        session.removeAttribute("SESSION_LOGIN_USER");
        return "user/login.vm";
    }
}
